#!/bin/bash

# 充电宝租赁系统启动和验证脚本
# 作者：AI Assistant
# 版本：1.0.0

echo "=================================="
echo "充电宝租赁系统启动和验证脚本"
echo "版本：1.0.0"
echo "=================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 基础目录
BASE_DIR=$(pwd)
LOG_DIR="$BASE_DIR/logs"

# 创建日志目录
mkdir -p $LOG_DIR

# 服务配置
SERVICES=(
    "powerbank-user-api:8081"
    "powerbank-admin-api:8082"
    "powerbank-device-service:8083"
)

# 依赖服务检查
echo -e "${YELLOW}1. 检查依赖服务状态...${NC}"

check_service() {
    local service_name=$1
    local port=$2
    echo -n "检查 $service_name ($port): "
    
    if command -v nc >/dev/null 2>&1; then
        if nc -z localhost $port >/dev/null 2>&1; then
            echo -e "${GREEN}运行中${NC}"
            return 0
        else
            echo -e "${RED}未运行${NC}"
            return 1
        fi
    else
        echo -e "${YELLOW}无法检查(nc命令不存在)${NC}"
        return 1
    fi
}

# 检查MySQL
check_service "MySQL" 3306

# 检查Redis
check_service "Redis" 6379

# 检查MQTT Broker (可选)
check_service "MQTT Broker" 1883

echo ""

# 编译项目
echo -e "${YELLOW}2. 编译项目...${NC}"
echo "开始Maven编译..."

if mvn clean compile -DskipTests > "$LOG_DIR/compile.log" 2>&1; then
    echo -e "${GREEN}项目编译成功${NC}"
else
    echo -e "${RED}项目编译失败，请检查日志: $LOG_DIR/compile.log${NC}"
    exit 1
fi

echo ""

# 启动服务函数
start_service() {
    local service_name=$1
    local service_dir="$BASE_DIR/$service_name"
    local port=$2
    
    echo "启动 $service_name..."
    
    if [ -d "$service_dir" ]; then
        cd "$service_dir"
        
        # 检查端口是否已被占用
        if nc -z localhost $port >/dev/null 2>&1; then
            echo -e "${YELLOW}端口 $port 已被占用，跳过启动 $service_name${NC}"
            return 1
        fi
        
        # 启动服务
        nohup mvn spring-boot:run > "$LOG_DIR/$service_name.log" 2>&1 &
        local pid=$!
        echo "$pid" > "$LOG_DIR/$service_name.pid"
        
        echo "服务 $service_name 已启动，PID: $pid"
        echo "日志文件: $LOG_DIR/$service_name.log"
        
        cd "$BASE_DIR"
        return 0
    else
        echo -e "${RED}服务目录不存在: $service_dir${NC}"
        return 1
    fi
}

# 启动所有服务
echo -e "${YELLOW}3. 启动微服务...${NC}"

for service_config in "${SERVICES[@]}"; do
    IFS=':' read -r service_name port <<< "$service_config"
    start_service "$service_name" "$port"
    
    # 等待服务启动
    echo "等待 $service_name 启动..."
    sleep 15
    
    # 验证服务是否启动成功
    if check_service "$service_name" "$port"; then
        echo -e "${GREEN}$service_name 启动成功${NC}"
    else
        echo -e "${RED}$service_name 启动失败${NC}"
    fi
    
    echo ""
done

echo ""

# API健康检查
echo -e "${YELLOW}4. API健康检查...${NC}"

check_api() {
    local api_name=$1
    local url=$2
    
    echo -n "检查 $api_name: "
    
    if command -v curl >/dev/null 2>&1; then
        response=$(curl -s -o /dev/null -w "%{http_code}" "$url" --connect-timeout 5)
        if [ "$response" = "200" ] || [ "$response" = "404" ] || [ "$response" = "401" ]; then
            echo -e "${GREEN}正常 (HTTP $response)${NC}"
        else
            echo -e "${RED}异常 (HTTP $response)${NC}"
        fi
    else
        echo -e "${YELLOW}无法检查(curl命令不存在)${NC}"
    fi
}

# 检查用户端API
check_api "用户端API" "http://localhost:8081/user-api/auth/test"
check_api "管理后台API" "http://localhost:8082/admin/sys-user/test"
check_api "设备服务API" "http://localhost:8083/device-service/device/status/TEST001"

echo ""

# 功能验证
echo -e "${YELLOW}5. 核心功能验证...${NC}"

if command -v curl >/dev/null 2>&1; then
    echo "测试设备状态查询..."
    curl -s "http://localhost:8083/device-service/monitor/health/TEST001" > /dev/null
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}设备监控功能正常${NC}"
    else
        echo -e "${RED}设备监控功能异常${NC}"
    fi
    
    echo "测试设备控制指令..."
    curl -s -X POST "http://localhost:8083/device-service/device/unlock/TEST001/1" > /dev/null
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}设备控制功能正常${NC}"
    else
        echo -e "${RED}设备控制功能异常${NC}"
    fi
else
    echo -e "${YELLOW}无法进行功能验证(curl命令不存在)${NC}"
fi

echo ""

# 显示系统状态
echo -e "${YELLOW}6. 系统状态总览${NC}"
echo "=================================="
echo "服务运行状态："

for service_config in "${SERVICES[@]}"; do
    IFS=':' read -r service_name port <<< "$service_config"
    printf "%-25s: " "$service_name"
    if nc -z localhost $port >/dev/null 2>&1; then
        echo -e "${GREEN}运行中 (端口 $port)${NC}"
    else
        echo -e "${RED}未运行${NC}"
    fi
done

echo ""
echo "日志文件位置: $LOG_DIR"
echo "=================================="

# 提供管理命令提示
echo -e "${YELLOW}管理命令：${NC}"
echo "查看服务日志: tail -f $LOG_DIR/[服务名].log"
echo "停止所有服务: ./scripts/stop-services.sh"
echo "重启服务: ./scripts/restart-services.sh"

echo ""
echo -e "${GREEN}系统启动完成！${NC}"
echo "用户端API: http://localhost:8081/user-api"
echo "管理后台API: http://localhost:8082/admin"
echo "设备服务API: http://localhost:8083/device-service"

exit 0